
## Load packages ##
library(readxl)
library(ggplot2) 
library(ggalt)   
library(tidyverse)
library(gridExtra)
library(ggtext)

## Read & sort data ##
R_import <- read_excel("[paste path]/R import Asia.xls")
R_import$income_grp <- as.numeric(R_import$income_grp)
is.numeric(R_import$income_grp)

R_import_ord <- R_import %>%
  arrange(income_grp, Q1) %>%  
  mutate(country = factor(country, levels = unique(country)))  

# Define a color palette for income groups
income_colors <- c("1" = "darkorchid", "2" = "darkgreen", "3" = "orange3", "4" = "deeppink")

# Create a custom labeling function for y-axis
custom_labels <- function(breaks) {
  labels <- breaks
  colors <- income_colors[as.character(R_import$income_grp[match(breaks, R_import$country)])]
  mapply(function(label, color) {
    paste0("<span style='color:", color, "'>", label, "</span>")
  }, labels, colors)
}

# Plot 
Equiplot <- ggplot() +
  geom_dumbbell(data = R_import_ord, 
                aes(y = fct_rev(country), x = Q1, xend = Q5),
                size = 1, color = "#b2b2b2", size_x = 1, size_xend = 1,
                colour_x = "red", colour_xend = "blue") +
  # Adding invisible points for legend
  geom_point(aes(x = 0, y = 0, color = "Q1"), show.legend = TRUE, size = 0) +
  geom_point(aes(x = 0, y = 0, color = "Q5"), show.legend = TRUE, size = 0) +
  scale_color_manual(name = "Wealth quintiles",
                     values = c("Q1" = "red", "Q5" = "blue"),
                     labels = c("Q1", "Q5")) +
  guides(color = guide_legend(override.aes = list(size = 1))) +
  labs(x = "GLP-1 receptor agonist eligibility (%)", y = NULL) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black", size=0.3),
        axis.text = element_text(colour = "black"), axis.ticks = element_line(colour = "black"),
        panel.grid.major.x = element_line(color = "lightgrey", size = 0.2),
        legend.position = c(0.85, 0.95),  
        legend.background = element_rect(fill = "white", color = "black"),
        legend.box.background = element_rect(fill = "white", color = "black"),
        legend.text = element_text(size = 8.5), 
        legend.title = element_text(size = 8.5, face="bold"), 
        legend.key.size = unit(0.3, "lines")) +
  scale_y_discrete(labels = custom_labels) +
  theme(
    axis.text.y = element_markdown()  # Use markdown for styling
  ) +
  scale_x_continuous(breaks = seq(0, 100, by = 10), limits = c(0, 102), expand = c(0, 0))


ggsave("Equiplot.pdf", plot = Equiplot, width = 6, height = 9)
